//
//  PrefsV2ViewController.m
//  FuelLog4
//
//  Created by Olaf on 10.05.10.
//  Copyright 2010 olafgreck. All rights reserved.
//

#import "PrefsV2ViewController.h"
#import "FuelLogAppDelegate.h"
#import "Pref.h"
#import "DebugOutput.h"
#import "BuildNumber.h"


@implementation PrefsViewController

@synthesize preferencesPrimaryArray;
@synthesize preferencesSecondaryArray;
@synthesize preferencesTitleArray;
@synthesize credentialsPrimaryArray;
@synthesize doneButton;
@synthesize userNameString, passWordString;
#pragma mark -


- (IBAction)done:(id)sender {
	Pref *pref = [FuelLogAppDelegate pref];
	[pref setPrefs:distanceDigits volumeDigits:volumeDigits+2 costDigits:costDigits+2 units:units];
	[self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -


- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
		doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
					  //style:UIBarButtonItemStylePlain
																   target:self
																   action:@selector(done:)];
		self.navigationItem.rightBarButtonItem = doneButton;
		self.navigationItem.title = (NSLocalizedString(@"Preferences", @"Preferences"));
		/*
		 #if TARGET_IPHONE_SIMULATOR
		 pwWrapper = nil;
		 #else 
		 pwWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"Google Password" accessGroup:@"UGMJ7YTNX2.com.olafgreck.FuelLog"];
		 #endif
		 */	
    }
	NSArray * unitsPrimaryArray = [[[NSArray alloc] initWithObjects:
									[NSString stringWithString:@"Miles per Gallon US"],
									[NSString stringWithString:@"Miles per Gallon UK"],
									[NSString stringWithString:@"Kilometer per Liter"], 
									[NSString stringWithString:@"Liter per 100km"], 
									[NSString stringWithString:@"Liter per 10km"],
									[NSString stringWithString:@"Dist. / fuel"], nil] autorelease];
	NSArray * DistanceDigitsPrimaryArray = [[[NSArray alloc] initWithObjects:
											 [NSString stringWithString:@"No decimal places"],
											 [NSString stringWithString:@"One decimal place"], nil] autorelease];
	NSArray * decimalPlacesArray = [[[NSArray alloc] initWithObjects:
									 [NSString stringWithString:@"Two decimal places"],
									 [NSString stringWithString:@"Three decimal places"], nil] autorelease];
	preferencesPrimaryArray = [[NSArray alloc] 
							   initWithObjects:unitsPrimaryArray,DistanceDigitsPrimaryArray,
							   decimalPlacesArray,decimalPlacesArray, nil];
	
	NSArray * unitsArray = [[[NSArray alloc] initWithObjects:[NSString stringWithString:@"US mpg"],
							 [NSString stringWithString:@"UK mpg"],
							 [NSString stringWithString:@"km/L"], 
							 [NSString stringWithString:@"L/100km"], 
							 [NSString stringWithString:@"L/10km"],
							 [NSString stringWithString:@"Dist. / fuel"], nil] autorelease];
	//	int currency = 100;
	NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
	[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
	//	NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithInt:currency]];
	
	NSArray * DistanceDigitsArray = [[[NSArray alloc] initWithObjects:
									  [NSString stringWithString:@"12345"],
									  [NSString stringWithString:@"12345,5"], nil] autorelease];
	NSArray * FuelDigitsArray = [[[NSArray alloc] initWithObjects:
								  [NSString stringWithString:@"12,34"],
								  [NSString stringWithString:@"12,345"], nil] autorelease];
	NSArray * CostDigitsArray = [[[NSArray alloc] initWithObjects:
								  [NSString stringWithString:@"123,45"],
								  [NSString stringWithString:@"123,456"], nil] autorelease];
	preferencesSecondaryArray = [[NSArray alloc] initWithObjects:unitsArray,DistanceDigitsArray, FuelDigitsArray,CostDigitsArray, nil];
	preferencesTitleArray = [[NSArray alloc] initWithObjects:
							 [NSString stringWithString:(NSLocalizedString(@"Units", @"Units "))],
							 [NSString stringWithString:(NSLocalizedString(@"Odometer Digits", @"Odometer Digits"))],
							 [NSString stringWithString:(NSLocalizedString(@"Volume Digits", @"Volume Digits"))],
							 [NSString stringWithString:(NSLocalizedString(@"Cost Digits", @"Cost Digits"))],
							 nil]; 
 	credentialsPrimaryArray = [[NSArray alloc] initWithObjects:
							   [NSString stringWithString:_onlineServiceNameGoogleDocs],							   
							   nil]; 
	
	return self;
}


/*
 - (void)viewDidLoad {
 [super viewDidLoad];
 
 // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
 // self.navigationItem.rightBarButtonItem = self.editButtonItem;
 }
 */


- (void)viewWillAppear:(BOOL)animated {
	debug(@"in viewWillAppear");
 	[(UIScrollView*)[self view] setScrollEnabled:NO];
	units = [FuelLogAppDelegate pref].units;
	distanceDigits = [FuelLogAppDelegate pref].odometerDigits;
	volumeDigits = [FuelLogAppDelegate pref].volumeDigits-2;
	costDigits = [FuelLogAppDelegate pref].costDigits-2;
	if (volumeDigits <0) volumeDigits = 0;
	if (costDigits <0) costDigits = 0;
	/*	 if (pwWrapper != nil) {
	 [pwWrapper setObject:userNameString forKey:(id)kSecAttrAccount];
	 [pwWrapper setObject:passWordString forKey:(id)kSecValueData];			
	 }
	 */
	[self.tableView reloadData];
	[self.navigationController setToolbarHidden:YES animated:YES];
	
	[super viewWillAppear:animated];
}

/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ 
	NSString * returnValue = @"";
	switch (section) {
		case section_UnitsAndDisplay:
			returnValue = (NSLocalizedString(@"Units & Display",@"Units & Display"));
			break;
		case section_OnlineAccounts:
			returnValue = (NSLocalizedString(@"Import/Export Accounts",@"Import/Export Accounts"));
			break;
			
		default:
			break;
			
	}
	return returnValue;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
	NSString * returnValue = @"";
	switch (section) {
		case section_UnitsAndDisplay:
			returnValue = nil;
			break;
		case section_OnlineAccounts:
			returnValue = @"";
			NSDictionary* infoDictionary = [[NSBundle mainBundle] infoDictionary];
			returnValue = (NSString *)[infoDictionary objectForKey:@"CFBundleDisplayName"];
			returnValue = [returnValue stringByAppendingString:@": Version "];
			returnValue = [returnValue stringByAppendingString:(NSString *)[infoDictionary objectForKey:@"CFBundleVersion"]];
			returnValue = [returnValue stringByAppendingString:@" Build: "];
			returnValue = [returnValue stringByAppendingString: kBuildNumber];
			break;
			
		default:
			break;
			
	}
	return returnValue;
}




- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return numberOfSections;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	int returnValue = 0;
	switch (section) {
		case section_UnitsAndDisplay:
			returnValue = section_Units_options;
			break;
		case section_OnlineAccounts:
			returnValue = section_OnlineAccounts_options;
			break;
		default:
			break;
	}
	return returnValue;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	NSInteger section = indexPath.section;
	NSInteger row = indexPath.row;
	static NSString *CellIdentifierType1 = @"CellIdentifier";
	UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierType1];
	if (cell == nil) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifierType1];
		cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
	}
	if (section ==section_UnitsAndDisplay) {
		cell.textLabel.text =  [preferencesTitleArray objectAtIndex:row];
		switch (row) {
			case prefRow_Units:
				cell.detailTextLabel.text =  [[preferencesSecondaryArray objectAtIndex:row] objectAtIndex:units];
				break;
			case prefRow_DistanceDigits:
				cell.detailTextLabel.text =  [[preferencesSecondaryArray objectAtIndex:row] objectAtIndex:distanceDigits];
				break;
			case prefRow_VolumeDigits:
				cell.detailTextLabel.text =  [[preferencesSecondaryArray objectAtIndex:row] objectAtIndex:volumeDigits];
				break;
			case prefRow_CostDigits:
				cell.detailTextLabel.text =  [[preferencesSecondaryArray objectAtIndex:row] objectAtIndex:costDigits];
				break;
			default:
				break;
		}
	}
	if (section ==section_OnlineAccounts ) 
	{
		cell.textLabel.text = [credentialsPrimaryArray objectAtIndex:row];
		NSError *error = nil;
		self.userNameString = [SFHFKeychainUtils  getPasswordForUsername:_username 
													 andServiceName:[credentialsPrimaryArray objectAtIndex:indexPath.row]
															  error:&error] ;
		if ([userNameString length] == 0 || error != 0) self.userNameString = @"<not assigned>";
		if (indexPath.row == prefRow_Username) cell.detailTextLabel.text = self.userNameString;
	}
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	//	[tableView deselectRowAtIndexPath:indexPath animated:NO];
	if (indexPath.section == section_UnitsAndDisplay) {
		prefsNumericSubViewController = [[PrefsNumericSubViewController alloc] initWithStyle:UITableViewStyleGrouped];
		[prefsNumericSubViewController setPreferencesPrimaryArray:[preferencesPrimaryArray objectAtIndex:indexPath.row]];
		[prefsNumericSubViewController setPreferencesSecondaryArray:[preferencesSecondaryArray objectAtIndex:indexPath.row]];
		[prefsNumericSubViewController setPreferencesTitleArray:[preferencesTitleArray objectAtIndex:indexPath.row]];
		[prefsNumericSubViewController setIndicatorForPreferenceToWorkOn:indexPath.row];
		[self.navigationController pushViewController:prefsNumericSubViewController animated:YES];
	}
	if (indexPath.section == section_OnlineAccounts) {
		prefsTextSubViewController = [[PrefsTextSubViewController alloc]initWithStyle:UITableViewStyleGrouped];
		[prefsTextSubViewController setAccountToWorkOn:[credentialsPrimaryArray objectAtIndex:indexPath.row]];
		
		[self.navigationController pushViewController:prefsTextSubViewController animated:YES];
		
	}
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


- (void)dealloc {
	[preferencesPrimaryArray release];
	[preferencesSecondaryArray release];
	[preferencesTitleArray release];
	[prefsNumericSubViewController release];
	[super dealloc];
}


@end

